<?php

namespace app\api\controller;

use app\api\controller\JwtService;
use think\admin\Controller;
use think\Request;
use think\facade\Db;
use think\Validate;

use Darabonba\OpenApi\OpenApiClient;
use AlibabaCloud\Darabonba\Stream\StreamUtil;
use AlibabaCloud\Tea\Utils\Utils;
use AlibabaCloud\Tea\Console\Console;

use Darabonba\OpenApi\Models\Config;
use Darabonba\OpenApi\Models\Params;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use Darabonba\OpenApi\Models\OpenApiRequest;


class Duoqudao extends Controller
{
    
    protected $middleware = [];
    //默认密码
    protected $default_pwd = '12345678';
    //密码盐
    protected $slat = 'wissun';
    //数据源
    protected  $storeconn="storeconn";
    
    //多级经销商签收表
    protected  $deliveryorder_sn="deliveryorder_sn";
    //经销商待入库单
    protected  $deliveryorder_order="deliveryorder_order";
    //经销商待入库单明细
    protected  $order_detail="deliveryorder_order_detail";
    
    protected  $wx_bos="jxs_lists";//经销商表包含网点
    //erpdb系统连接标识
    protected $erpdb="erpdb";
    //经销商发货单明细
    protected $deliveryorder_wdfahuo="deliveryorder_fahuo_detail";
    //经销商发货单
    protected $deliveryorder_fahuo="deliveryorder_fahuo";
    
    //阿里云请求key
    protected $access_key_id="LTAI5tB9L7HacboZsvvjcVBn";
    //阿里云请求秘钥
    protected $access_key_secret="3SUXHPRl25J5KAJGA3p1kpzUaI6iYW";
    //网点入库单编号前缀
    protected $wdbh_exp="wdch";
    
    public function demotest(){
        $jxscode=input("jxs_code","13696611963");
        $yyaa='1340604,1371729,1360929,1350426,3621218,1371810,1350205,1442013,1450507,1331113,1440812,1440127,1350623';
        $yyaa="2340605263";
        $aa=explode(",",$yyaa);
        echo '<link rel="stylesheet" href="http://layui.apixx.net/res/layui/dist/css/layui.css"   media="all"><table class="layui-table" border="1">';
        foreach ($aa as $rrr=>$jxscode){
            $o["custcode"]=$jxscode;
            $de=Db::connect($this->storeconn)
            ->name($this->deliveryorder_order)
            ->where($o)
            ->order("deliveryorderno desc")
            ->select();
            $accp_product_arr=get_duoqu_product_show();
            $alldetail=[];$isfahuo_count=0;$hhc=0;
            foreach ($de as $k=>$vv){
                $hw["order_no"]=$vv["deliveryorderno"];
                $box_detail=Db::connect($this->storeconn)->name($this->order_detail)->where($hw)->select(); 
                foreach ($box_detail as $yk=>$vak){
                    //检查产品料号
                    if(isset($accp_product_arr[$vak["productcd"]])){
                        //检查产品的批次
                        $a=$accp_product_arr[$vak["productcd"]];
                        if($a["batch"]){
                            $batchno=get_product_batchno($vak["batchno"]);
                            if($batchno < $a["batch"]){
                                unset($box_detail[$yk]);
                                continue;
                            }
                        }
                        $box_detail[$yk]=$vak;
                    }else{
                        unset($box_detail[$yk]);
                        continue;
                    }
                }
                if(empty($box_detail)){
                   unset($de[$k]);
                   continue;
                }
                $box_detail=array_values($box_detail);
                $boxcode=0;$sncode=0;$ucode=[];
                $ubath=[];
                foreach($box_detail as $yya=>$rkq){
                    if($rkq["code_type"] == 2){
                        //查询箱中每一罐是否已经发货了
                        $countss=Db::connect($this->erpdb)->name("v_code")->where("BoxCode",$rkq["code"])->count();
                        if($countss){
                            $hhc+=$countss;
                        }
                        $boxcode++;
                    }else{
                        $hhc++;
                        $sncode++;
                    }
                    if(in_array($rkq["productcd"],$ucode)){
                        $ubath[$rkq["productcd"]][]=$rkq;
                    }else{
                        array_push($ucode,$rkq["productcd"]);
                        $ubath[$rkq["productcd"]][]=$rkq;
                    }
                }
                $ubaths=[];$newdata=[];
                $snlists=[];
                //计算每个批次有多少货
                foreach($ubath as $yy=>$ty){
                    //循环每一个料号
                    $batchs=[];//包含多个批次和数据集
                    foreach ($ty as $yy2=>$ty2){
                        if(in_array($ty2["batchno"],$batchs)){
                            $ubaths[$ty2["batchno"]][]=$ty2;
                        }else{
                            array_push($batchs,$ty2["batchno"]);
                            $ubaths[$ty2["batchno"]][]=$ty2;
                        }
                        
                    }
                    //循环多个批次
                    foreach($ubaths as $tt=>$vt){
                        $g=$vt[0];
                        $g["batchno"]=$tt;
                        $g["total_count"]=count($vt);//批次的总数
                        array_push($newdata,$g);
                    }
                }
                $vv["boxcode"]=$boxcode;
                $vv["sncode"]=$sncode;
                $vv["box_detail"]=$newdata;
                $de[$k]=$vv;
            }
            $de=array_values($de);
            $d=Db::connect($this->storeconn)->name("deliveryorder_fahuo_detail")->where("custcode",$jxscode)->count();
            
            echo "<tr><td>经销商编号：".$jxscode."<td>";
            echo "<td>收货罐数：".$hhc."<td>";
            echo "<td>发货罐数：".$d."<td>";
            echo "<td>剩余罐数：".($hhc-$d)."<td></tr>";
        }
        echo "</table>";
    }
    /**
     * 多渠道经销商登陆
     * @param int username 登录账号
     * @param string $password 登陆密码
     */
    public function login()
    {
        $param = $this->request->param();
        $validate = new Validate([
            'username' => 'require',
            'password' => 'require'    
        ]);
        $check_res = $validate->check($param);
        if (!$check_res) {
            return json(['code' => 0, 'message' => $validate->getError()]);
        }
       
        $wd_account = Db::name('jxs_lists')->where(['username' => $param['username']])->find();
        if (empty($wd_account)) {
            return json(['code' => 0, 'message' => '账号不存在,请核对后再试']);
        }
        if ($wd_account['password'] != $param['password']) {
            return json(['code' => 0, 'message' => '密码错误，请重试或联系客服。']);
        }
        unset($wd_account['password']);
        $token = JwtService::create_token($wd_account);
        //查询账户绑定的网点信息，如果有多个网点，则让用户选择网点
        // $wxbox=1;
        // if(in_array(4,$roleids)){
        //     $whwx["bossphone"]=$wd_account["username"];
        //     $wxbox=Db::connect($this->storeconn)->name($this->wx_bos)->where($whwx)->count();
        // }
        Db::name('jxs_lists')->where("id",$wd_account["id"])->update(["login_time"=>date("Y-m-d H:i:s")]);
        return json(['code' => 200, 'message' => '登陆成功', 'token' => $token,"userinfo"=>$wd_account]);
    }
    
    
    //获取账户下面的所有网点列表
    public function wdstore_list(){
        $param = $this->request->param();
        $validate = new Validate([
            'user_id' => 'require'
        ]);
        $check_res = $validate->check($param);
        if (!$check_res) {
            return json(['code' => 0, 'message' => $validate->getError()]);
        }
        $wdinfo=Db::name($this->wx_bos)->where("id",$param["user_id"])->find();
        if($wdinfo["role"]){
            $whwx["parent_id"]=$param["user_id"];
        }else{
            $whwx["parent_id"]=24;
        }
        if(isset($param["keywords"])){
            $wxbox=Db::name($this->wx_bos)->where($whwx)->where("role",">",0)->field("user_code,nickname as username,role,detail,latitude,longitude")->where("nickname",'like','%'.$param["keywords"]."%")->select();
        }else{
            $wxbox=Db::name($this->wx_bos)->where($whwx)->where("role",">",0)->field("user_code,nickname as username,role,detail,latitude,longitude")->select();
        }
        return json(['code' => 200, 'message' => '获取成功',"data"=>$wxbox]);
    }
    
    //写入经销商的库存表中
    function demo_jxs_qssn($jxs_code="",$deliveryorderno=""){
        //写入用户库存表
        $gdata=Db::connect($this->storeconn)->name("deliveryorder_order_detail")->where("order_no",$deliveryorderno)->select();
        $goodscode=[];//箱数集
        $sncodelist=[];//罐数集
        $accp_product_arr=get_duoqu_product_show();
        foreach($gdata as $gg=>$gh){
            if($gh["code_type"] == 2){ //箱码
                //检查产品料号,过滤不要展示的产品
                if(isset($accp_product_arr[$gh["productcd"]])){
                    //检查产品的批次
                    $a=$accp_product_arr[$gh["productcd"]];
                    if($a["batch"]){
                        //有批次限制，判断限制
                        $batchno=get_product_batchno($gh["batchno"]);
                        if($batchno >= $a["batch"]){
                            $vcodelist=Db::connect($this->erpdb)->name("v_code")->where("BoxCode",$gh["code"])->select();
                            foreach ($vcodelist as $kak=>$vav){
                                  $prwhere["product_code"]=$vav["ProductCD"];
                                  $prwhere["batchno"]=$vav["BatchNO"];
                                  $prwhere["product_size"]=$vav["Norm"];
                                  $prwhere["jxs_code"]=$jxs_code;
                                  $re=Db::connect($this->storeconn)->name("product_kucun")->where($prwhere)->find();
                                  if($re){
                                      Db::connect($this->storeconn)->name("product_kucun")->where($prwhere)->setInc("sn_count",1);
                                      continue;
                                  }else{
                                      $add["product_code"]=$vav["ProductCD"];
                                      $add["batchno"]=$vav["BatchNO"];
                                      $add["product_size"]=$vav["Norm"];
                                      $add["product_name"]=$vav["ProductName"];
                                      $add["jxs_code"]=$jxs_code;
                                      $add["sn_count"]=1;
                                      $add["type"]=1;
                                      Db::connect($this->storeconn)->name("product_kucun")->insert($add);
                                  }
                            }
                        }
                    }else{
                        //没有批次限制
                        $vcodelist=Db::connect($this->erpdb)->name("v_code")->where("BoxCode",$gh["code"])->select();
                        foreach ($vcodelist as $kak=>$vav){
                              $prwhere["product_code"]=$vav["ProductCD"];
                              $prwhere["batchno"]=$vav["BatchNO"];
                              $prwhere["product_size"]=$vav["Norm"];
                              $prwhere["jxs_code"]=$jxs_code;
                              $re=Db::connect($this->storeconn)->name("product_kucun")->where($prwhere)->find();
                              if($re){
                                  Db::connect($this->storeconn)->name("product_kucun")->where($prwhere)->setInc("sn_count",1);
                                  continue;
                              }else{
                                  $add["product_code"]=$vav["ProductCD"];
                                  $add["batchno"]=$vav["BatchNO"];
                                  $add["product_size"]=$vav["Norm"];
                                  $add["product_name"]=$vav["ProductName"];
                                  $add["jxs_code"]=$jxs_code;
                                  $add["sn_count"]=1;
                                  $add["type"]=1;
                                  Db::connect($this->storeconn)->name("product_kucun")->insert($add);
                              }
                        }
                    }
                }
            }else if($gh["code_type"]==1){ //罐码
                 $add["product_code"]=$gh["productcd"];
                 $add["batchno"]=$gh["batchno"];
                 $add["product_size"]=$gh["norm"];
                 $add["product_name"]=$gh["product_name"];
                 $add["jxs_code"]=$jxs_code;
                 $add["sn_count"]=1;//增加一罐
                 $add["count"]=0;//箱
                 //检查产品料号,过滤不要展示的产品
                if(isset($accp_product_arr[$gh["productcd"]])){
                    //检查产品的批次
                    $a=$accp_product_arr[$gh["productcd"]];
                    if($a["batch"]){
                        //有批次限制，判断限制
                        $batchno=get_product_batchno($gh["batchno"]);
                        if($batchno >= $a["batch"]){
                              $vcodelist=Db::connect($this->erpdb)->name("v_code")->where("TrackCode",$gh["code"])->find();
                              $prwhere["product_code"]=$vav["ProductCD"];
                              $prwhere["batchno"]=$vav["BatchNO"];
                              $prwhere["product_size"]=$vav["Norm"];
                              $prwhere["jxs_code"]=$jxs_code;
                              $re=Db::connect($this->storeconn)->name("product_kucun")->where($prwhere)->find();
                              if($re){
                                  Db::connect($this->storeconn)->name("product_kucun")->where($prwhere)->setInc("sn_count",1);
                                  continue;
                              }else{
                                  $add["product_code"]=$vav["ProductCD"];
                                  $add["batchno"]=$vav["BatchNO"];
                                  $add["product_size"]=$vav["Norm"];
                                  $add["product_name"]=$vav["ProductName"];
                                  $add["jxs_code"]=$jxs_code;
                                  $add["sn_count"]=1;
                                  $add["type"]=1;
                                  Db::connect($this->storeconn)->name("product_kucun")->insert($add);
                              }
                        }
                    }else{
                          //没有批次限制
                          $vcodelist=Db::connect($this->erpdb)->name("v_code")->where("TrackCode",$gh["code"])->find();
                          $prwhere["product_code"]=$vav["ProductCD"];
                          $prwhere["batchno"]=$vav["BatchNO"];
                          $prwhere["product_size"]=$vav["Norm"];
                          $prwhere["jxs_code"]=$jxs_code;
                          $re=Db::connect($this->storeconn)->name("product_kucun")->where($prwhere)->find();
                          if($re){
                              Db::connect($this->storeconn)->name("product_kucun")->where($prwhere)->setInc("sn_count",1);
                              continue;
                          }else{
                              $add["product_code"]=$vav["ProductCD"];
                              $add["batchno"]=$vav["BatchNO"];
                              $add["product_size"]=$vav["Norm"];
                              $add["product_name"]=$vav["ProductName"];
                              $add["jxs_code"]=$jxs_code;
                              $add["sn_count"]=1;
                              $add["type"]=1;
                              Db::connect($this->storeconn)->name("product_kucun")->insert($add);
                          }
                    }
                }
            }
        }
    }
    
    //扫码签收收货单-经销商-分销网点
    public function saoma_shouhuo_order(){
        $deliveryorderno= $this->request->param('order_no');
        $boxcode= $this->request->param('code');
        $trt=substr($boxcode,0,20);
        if($trt == "http://weixin.qq.com"){
             return json(['code' => 1, 'message' =>"请遮住箱子下面的微信二维码再扫~"]);
        }
        $jxs_code= $this->request->param('jxs_code');
        $system_user= $this->request->param('system_user');
        $latitude= $this->request->param('latitude');
        $longitude= $this->request->param('longitude');
        $city= $this->request->param('city');
        $province= $this->request->param('province');
        $nation= $this->request->param('nation');
        
        //判断网点的经纬度，如果没有经纬度信息，则新增，不判断范围，如果已经存在，则需要判断范围3公里，超过3公里则提示与首次定位距离超过3公里
        $wxbox=Db::name("jxs_lists")->where("user_code",$jxs_code)->find();
        if(empty($wxbox["s_city"])){
            $upwxbox["s_latitude"]=$latitude;
            $upwxbox["s_longitude"]=$longitude;
            $upwxbox["s_city"]=$city;
            $upwxbox["s_province"]=$province;
            $upwxbox["s_county"]=$nation;
            $upwxbox["s_time"]=date("Y-m-d H:i:s");
            Db::name("jxs_lists")->where("user_code",$jxs_code)->update($upwxbox);
        }
        Db::startTrans();
        //网点出货单号
        $trq["wdbh"]=$jxs_code;
        $trq["order_no"]=$deliveryorderno;
        $rar=Db::name("deliveryorder_fahuo")->where($trq)->find();
        if(empty($rar)){
              return json(['code' => 1, 'message' =>"该罐码不在此次签收名单中~~"]);
        }
        //是否存在签收表中，存在则代表已经签收了
        if($rar["is_qianshou"] == 1){
             return json(['code' => 1, 'message' =>"已验收无需重复验收"]);
        }
        //罐码判断
        $http=substr($boxcode,0,4);
        if($http == "http"){
            //罐码
            $boxcode=substr($boxcode,33);
            //检测货物箱码是否归属此次的经销商
            $yw["sncode"]=$boxcode;
            $yw["wdbh"]=$jxs_code;
            $yw["order_no"]=$deliveryorderno;
            $tr=Db::name($this->deliveryorder_wdfahuo)->where($yw)->find();
            if(empty($tr)){
                return json(['code' => 1, 'message' =>"该罐码不属于您,请核对后再试~",]);
            }
        }
        else{
            //箱码
            $attr=substr($boxcode,0,5);
            if($attr == "12345"){
                $boxcode=substr($boxcode,5);
            }
            $yw["boxcode"]=$boxcode;
            $yw["wdbh"]=$jxs_code;
            $yw["order_no"]=$deliveryorderno;
            $tr=Db::name($this->deliveryorder_wdfahuo)->where($yw)->find();
            if(empty($tr)){
                return json(['code' => 1, 'message' =>"该箱码不属于您,请核对后再试~",]);
            }
        }
        
        $uqian2["is_qianshou"]=1;
        $uqian2["scan_code"]=$boxcode;
        $uqian2["qs_time"]=time();
        Db::name($this->deliveryorder_fahuo)->where($trq)->update($uqian2);//修改发货表标识
        
        $uqian["is_qianshou"]=1;
        $uqian["qs_time"]=time();
        Db::name($this->deliveryorder_wdfahuo)->where($trq)->update($uqian);//修改发货明细表标识
        
        //写入用户的产品库存
        $yw2["wdbh"]=$jxs_code;
        $yw2["order_no"]=$deliveryorderno;
        $tr=Db::name("deliveryorder_fahuo_detail")->where($yw2)->select();
        foreach ($tr as $kk=>$val){
            $uwhere["jxs_code"]=$jxs_code;
            $uwhere["product_code"]=$val["product_code"];
            $uwhere["product_name"]=$val["product_name"];
            $uwhere["product_size"]=$val["product_size"];
            $uwhere["batchno"]=$val["batch"];
            $ufdata=Db::name("product_kucun")->where($uwhere)->find();
            if($ufdata){
                Db::name("product_kucun")->where($uwhere)->inc("sn_count",1)->update();
            }else{
                $uwhere2["jxs_code"]=$jxs_code;
                $uwhere2["product_code"]=$val["product_code"];
                $uwhere2["product_name"]=$val["product_name"];
                $uwhere2["product_size"]=$val["product_size"];
                $uwhere2["batchno"]=$val["batch"];
                $uwhere2["sn_count"]=1;
                Db::name("product_kucun")->insert($uwhere2);
            }
            
            $isjxskucun=Db::name("jxs_kucun")->where(["jxs_code"=>$jxs_code,"sncode"=>$val["sncode"],"is_send"=>0])->find();
            if(empty($isjxskucun)){
                $inadd["sncode"]=$val["sncode"];
                $inadd["jxs_code"]=$jxs_code;
                $inadd["add_time"]=date("Y-m-d H:i:s");
                $inadd["is_send"]=0;
                $inadd["boxcode"]=$val["boxcode"];
                $inadd["ProductCD"]=$val["product_code"];
                $inadd["ProductName"]=$val["product_name"];
                $inadd["Norm"]=$val["product_size"];
                $inadd["ProductLine"]="-";
                $inadd["ProductionDate"]="-";
                $inadd["BatchNO"]=$val["batch"];
                $inadd["Unit"]="听";
                Db::name("jxs_kucun")->insert($inadd);
            }
        }
        Db::commit();
        return json(['code' =>200, 'message' =>"签收成功~"]);
    }
    
    //经销商扫码签收
    public function jxs_shouhuo_order(){
        $deliveryorderno= $this->request->param('order_no');
        $jxs_code= $this->request->param('jxs_code');
        $system_user= $this->request->param('system_user');
        Db::startTrans();
        $trq["wdbh"]=$jxs_code;
        $trq["order_no"]=$deliveryorderno;
        $uqian2["is_qianshou"]=1;
        $uqian2["qs_time"]=time();
        Db::name($this->deliveryorder_fahuo)->where($trq)->update($uqian2);//修改发货表标识
        
        $uqian["is_qianshou"]=1;
        $uqian["qs_time"]=time();
        Db::name($this->deliveryorder_wdfahuo)->where($trq)->update($uqian);//修改发货明细表标识
        
          //写入用户的产品库存
        $yw2["wdbh"]=$jxs_code;
        $yw2["order_no"]=$deliveryorderno;
        $tr=Db::name($this->deliveryorder_wdfahuo)->where($yw2)->select();
        foreach ($tr as $kk=>$val){
            $uwhere["jxs_code"]=$jxs_code;
            $uwhere["product_code"]=$val["product_code"];
            $uwhere["product_name"]=$val["product_name"];
            $uwhere["product_size"]=$val["product_size"];
            $uwhere["batchno"]=$val["batch"];
            $ufdata=Db::name("product_kucun")->where($uwhere)->find();
            if($ufdata){
                Db::name("product_kucun")->where($uwhere)->inc("sn_count",1)->update();
            }else{
                $uwhere2["jxs_code"]=$jxs_code;
                $uwhere2["product_code"]=$val["product_code"];
                $uwhere2["product_name"]=$val["product_name"];
                $uwhere2["product_size"]=$val["product_size"];
                $uwhere2["batchno"]=$val["batch"];
                $uwhere2["sn_count"]=1;
                Db::name("product_kucun")->insert($uwhere2);
            }
            
            $isjxskucun=Db::name("jxs_kucun")->where(["jxs_code"=>$jxs_code,"sncode"=>$val["sncode"],"is_send"=>0])->find();
            if(empty($isjxskucun)){
                $inadd["sncode"]=$val["sncode"];
                $inadd["jxs_code"]=$jxs_code;
                $inadd["add_time"]=date("Y-m-d H:i:s");
                $inadd["is_send"]=0;
                $inadd["boxcode"]=$val["boxcode"];
                
                $inadd["ProductCD"]=$val["product_code"];
                $inadd["ProductName"]=$val["product_name"];
                $inadd["Norm"]=$val["product_size"];
                $inadd["ProductLine"]="-";
                $inadd["ProductionDate"]="-";
                $inadd["BatchNO"]=$val["batch"];
                $inadd["Unit"]="听";
                
                Db::name("jxs_kucun")->insert($inadd);
            }
        }
        Db::commit();
        return json(['code' =>200, 'message' =>"签收成功~"]);
    }
    
    //经销商待签收列表
    public function jxsnoqianshou(){
        $param = $this->request->param();
        $validate = new Validate([
            'jxs_code' => 'require'
        ]);
        $check_res = $validate->check($param);
        if (!$check_res) {
            return json(['code' => 0, 'message' => $validate->getError()]);
        }
        $jxs_code= $this->request->param('jxs_code');
        $o["wdbh"]=$jxs_code;
        $o["is_qianshou"]=0;
        $de=Db::name($this->deliveryorder_fahuo)
        ->where($o)
        ->order("deliveryorderno desc")
        ->select();
        foreach($de as $kk=>$vv){
            $vv["outdate"]=$vv["add_time"];
            $vv["deliveryorderno"]=$vv["order_no"];
            $hw["order_no"]=$vv["order_no"];
            $box_detail2=Db::name($this->deliveryorder_wdfahuo)->group("product_code")->field("*,count(1) as count")->where($hw)->select();
            $vv["box_detail"]=$box_detail2;
            $role=Db::name("jxs_lists")->where("user_code",$vv["wdbh"])->value("role");
            $vv["role"]=$role;
            $de[$kk]=$vv;
        }
         return json(['code' => 200, 'data' => $de]);
    }
    
    //经销商的签收单
    public function jxsnoqianshou2(){
        $param = $this->request->param();
        $validate = new Validate([
            'user_id' => 'require'
        ]);
        $check_res = $validate->check($param);
        if (!$check_res) {
            return json(['code' => 200, 'message' => $validate->getError()]);
        }
        $user_id= $this->request->param('user_id');
        $datalist=[];
        if($user_id){
            $wdinfo=Db::name($this->wx_bos)->where("id",$user_id)->find();
            if($wdinfo["role"]){
                $datalist=Db::name("deliveryorder_fahuo")->where("is_qianshou",1)->where("wdbh",$wdinfo["user_code"])->order("id desc")->page($param["page"])->limit($param["limit"])->select();
                foreach ($datalist as $kk=>$val){
                    $val["box_detail"]=Db::name("deliveryorder_fahuo_detail")->where("order_no",$val["order_no"])->field("*,count(1) as count")->group("product_code")->select();
                    $datalist[$kk]=$val;
                }
            }
        }
        return json(['code' => 200, 'message' => 'success',"datalist"=>$datalist]);
    }    
    
    //解绑网点信息
    public function jiebang_wd_info(){
        $jxs_code = $this->request->param('jxs_code');
        $wdbh = $this->request->param('wdbh');
        $curr_role=$this->request->param('role');
        if($jxs_code && $wdbh ){
            //查询发货记录
            $is_delete=Db::connect($this->storeconn)->name("deliveryorder_fahuo")->where(["wdbh"=>$wdbh,"jxs_code"=>$jxs_code])->find();
            if(empty($is_delete)){
                $rr=Db::connect($this->storeconn)->name($this->wx_bos)->where("netcode",$wdbh)->delete();
                if($rr){
                    Db::connect($this->storeconn)->name("system_user")->where("contact_jxscode",$wdbh)->delete();
                }
                $inst["add_time"]=date("Y-m-d H:i:s");
                $inst["wdbh"]=$wdbh;
                Db::connect($this->storeconn)->name("jiebang_log")->insert($inst);
                return json(['code' => 1, 'message' => "删除网点操作成功"]);
            }
        }
        return json(['code' => 0, 'message' => "不符合删除操作"]);
    }
    
    //绑定已有网点信息
    public function bind_ready_wdinfo(){
        $jxs_code = $this->request->param('jxs_code');
        $wdbh = $this->request->param('wdbh');
        $curr_role=$this->request->param('role');
        $to_wdbh=$this->request->param('to_wdbh');
        //第一步获取已有的网点编号
        $wdinfo=Db::connect($this->storeconn)->name("wx_bos")->where("netcode",$wdbh)->find();
        if($wdinfo){
            //发货的单表-修改
            $update31["wdbh"]=$to_wdbh;
            $a=Db::connect($this->storeconn)->name("deliveryorder_fahuo")->where(["wdbh"=>$wdbh])->update($update31);
            
            //发货码中间表
            $updda["wdbh"]=$to_wdbh;
            $a2=Db::connect($this->storeconn)->name("deliveryorder_fahuo_code")->where(["wdbh"=>$wdbh])->update($updda);
            
            //发货明细
            $upd["wdbh"]=$to_wdbh;
            $a3=Db::connect($this->storeconn)->name("deliveryorder_fahuo_detail")->where(["wdbh"=>$wdbh])->update($upd);
            
            
            //库存表
            $up["jxs_code"]=$to_wdbh;
            $a4=Db::connect($this->storeconn)->name("product_kucun")->where(["jxs_code"=>$wdbh])->update($up);
            
            
            //申请退货表
            $update3["uid"]=$to_wdbh;
            $a5=Db::connect($this->storeconn)->name("return_apply")->where(["uid"=>$wdbh])->update($update3);
            
             //申请退货表
            $update2["uid"]=$to_wdbh;
            $a6=Db::connect($this->storeconn)->name("return_apply")->where(["uid"=>$wdbh])->update($update2);
            //申请退货明细
            $up2e2["uid"]=$to_wdbh;
            $a7=Db::connect($this->storeconn)->name("return_apply_detail")->where(["uid"=>$wdbh])->update($up2e2);
            
            //系统用户表
            $up222["contact_jxscode"]=$to_wdbh;
            $a8=Db::connect($this->storeconn)->name("system_user")->where(["contact_jxscode"=>$wdbh])->update($up222);
            
            $ucap222["netcode"]=$to_wdbh;
            $a9=Db::connect($this->storeconn)->name("wx_bos")->where(["netcode"=>$wdbh])->update($ucap222);
            
            //删除未认证的网点
            //$a10=Db::connect($this->storeconn)->name("wx_bos")->where(["netcode"=>$to_wdbh])->delete();
            //替换原有的网点-修改网点编号
            $ucap222["netcode"]=$to_wdbh;
            $a11=Db::connect($this->storeconn)->name("wx_bos")->where(["netcode"=>$wdbh])->update($ucap222);
            //修改下级网点中出现上级网点编号
            $ucap552["parent_netcode"]=$to_wdbh;
            $a12=Db::connect($this->storeconn)->name("wx_bos")->where(["parent_netcode"=>$wdbh])->update($ucap552);
            // deliveryorder_fahuo
            // deliveryorder_fahuo_code
            // deliveryorder_fahuo_detail
            // product_kucun
            // return_apply
            // return_apply_detail
            // system_user
            // wx_bos
            //echo "a1=".$a."=a2=".$a2."=a3=".$a3."=a4=".$a4."=a5=".$a5.'=a6='.$a6."=a7=".$a7."=a8=".$a8."=a9=".$a9."=a10=".$a10."=a11=".$a11."=a12=".$a12;
            return json(['code' => 1, 'message' => "绑定成功"]);
        }
        return json(['code' => 0, 'message' => "未找到网点信息"]);
    }
    
    //经销商下属网点列表 
    public function wdbh_list(){
        $jxs_code = $this->request->param('jxs_code');
        $wdname = $this->request->param('wdname');
        $wdbh = $this->request->param('wdbh');
        $wdlist2=[];
        $wdlist =Db::name($this->wx_bos)->field("id,user_code,username,role")
        ->where(function ($query) use ($jxs_code) {
            $query->where("parent_id",$jxs_code);
        })->where(function ($query) use ($wdbh) {
            if($wdbh){
                $query->whereor("user_code","like",'%'.$wdbh.'%');
                $query->whereor("username","like",'%'.$wdbh.'%');
            }
        })->order("id desc")
        ->select();
        
        return json(['code' => 200,'data' => $wdlist]);
    }
    
    //经销商下属网点列表 -已认证列表
    public function wdbh_list_yirenzhen(){
        $jxs_code = $this->request->param('jxs_code');
        $wdname = $this->request->param('wdname');
        $wdbh = $this->request->param('wdbh');
        $curr_role=$this->request->param('role');
       
        $curr_role=explode(",",$curr_role);
        if(in_array(1,$curr_role) || in_array(8,$curr_role)){
            $wdlist = Db::connect($this->storeconn)->name($this->wx_bos)->field("id,netcode,netname,netaddr")->where(function ($query) use ($jxs_code) {
                $query->where("multidealercode",'like','%'.$jxs_code."%");
                $query->where("parent_netcode",null);
            })->where(function ($query) use ($wdbh) {
                if($wdbh){
                    $query->whereor("netcode","like",'%'.$wdbh.'%');
                    $query->whereor("netname","like",'%'.$wdbh.'%');
                }
            })->order("id desc")->select();
        }
        else{
            $wdlist =Db::connect($this->storeconn)->name($this->wx_bos)->field("id,netcode,netname,netaddr")->where(function ($query) use ($jxs_code) {
                $query->where("parent_netcode",$jxs_code);
            })->where(function ($query) use ($wdbh) {
                if($wdbh){
                    $query->whereor("netcode","like",'%'.$wdbh.'%');
                    $query->whereor("netname","like",'%'.$wdbh.'%');
                }
            })->order("id desc")->select();
        }
        $netcode_arr=[];
        foreach($wdlist as $kk=>$val){
            $wh["tc_qss01"]=$val["dealercode"];//经销商
            $product=Db::connect($this->erpdb)->name("localtcqssfile")->where("tc_qss04","in",$val["product"])->where($wh)->select();
            $val["productlist"]=$product;
            //查询发货记录
            $is_delete=Db::connect($this->storeconn)->name("deliveryorder_fahuo")->where(["wdbh"=>$val["netcode"]])->find();
            if($is_delete){
                $val["is_delete"]=0;
            }else{
                $val["is_delete"]=1;
            }
            $username=Db::connect($this->storeconn)->name("system_user")->where("contact_jxscode",$val["netcode"])->value("username");
            $val["username"]=$username;
            $wdlist[$kk]=$val;
            array_push($netcode_arr,$val["netcode"]);
        }
        return json(['code' => 1, 'data' => $wdlist]);
    }
    
     //经销商下属网点列表 -未认证
    public function wdbh_list_weirenzhen(){
        $jxs_code = $this->request->param('jxs_code');
        $wdname = $this->request->param('wdname');
        $wdbh = $this->request->param('wdbh');
        $curr_role=$this->request->param('role');
       
        $curr_role=explode(",",$curr_role);
        $wdlist=[];$wdlist3=[];
        if(in_array(1,$curr_role) || in_array(8,$curr_role)){
            $wdlist = Db::name($this->wx_bos)->field("id,netcode,netname,netaddr")->where(function ($query) use ($jxs_code) {
                $query->where("multidealercode","like","%".$jxs_code."%");
            })->where(function ($query) use ($wdbh) {
                if($wdbh){
                    $query->whereor("netcode","like",'%'.$wdbh.'%');
                    $query->whereor("netname","like",'%'.$wdbh.'%');
                }
            })->order("id desc")->where("wdstatus",1)->select();
            
            $wdlist3 = Db::connect($this->storeconn)->name($this->wx_bos)->field("id,netcode,netname,netaddr")
            ->where(function ($query) use ($jxs_code) {
                $query->where("multidealercode",'like','%'.$jxs_code."%");
                $query->where("parent_netcode",null);
            })
            ->where(function ($query) use ($wdbh) {
                if($wdbh){
                    $query->whereor("netcode","like",'%'.$wdbh.'%');
                    $query->whereor("netname","like",'%'.$wdbh.'%');
                }
            })
            ->order("id desc")->select();
            
        }
        $netcode_arr=[];
        foreach($wdlist as $kk=>$val){
            array_push($netcode_arr,$val["netcode"]);
        }
        if($wdlist3){
            foreach($wdlist3 as $kk=>$val){
                $val["r_status"]="未认证";
                if(in_array($val["netcode"],$netcode_arr)){
                    $val["r_status"]="已认证";
                    unset($wdlist3[$kk]);
                    continue;
                }
                $wdlist3[$kk]=$val;
            }
            $wdlist3=array_values($wdlist3);
        }
        return json(['code' => 1, 'data' => $wdlist3,"data2"=>$wdlist]);
    }
    
    //查询经销商库存情况
    public function store_kuchun_his_new(){
        $jxs_code = $this->request->param('jxs_code');
        $page= $this->request->param('page',1);
        $size= $this->request->param('size',5);       
        $curr_role=$this->request->param('role');
        $roles=[1,4,5,6,7];
        if(!in_array($curr_role,$roles)){
             return json(['code' => 0, 'message' => "用户角色不存在"]);
        }
        if($curr_role == 1){
           $wh["jxs_code"]=$jxs_code;
           $lists=Db::connect($this->storeconn)->name($this->deliveryorder_sn)->where($wh)->page($page)->limit($size)->order("id desc")->select();
           foreach ($lists as $k=>$v){
              if($v["boxcode"]){ $v["scan_code"]=$v["boxcode"];  }
              if($v["sncode"]){  $v["scan_code"]=$v["sncode"];  }
              $lists[$k]=$v;
           }
        }else{
           $wh["wdbh"]=$jxs_code;
           $wh["is_qianshou"]=1;
           $lists=Db::connect($this->storeconn)->name($this->deliveryorder_fahuo)->where($wh)->page($page)->limit($size)->order("id desc")->select();
           foreach ($lists as $k=>$v){
               $v["total_count"]=($v["sncode"])?$v["sncode"]:0;
               $v["total_boxcode"]=($v["boxcode"])?$v["boxcode"]:0;
               $v["deliveryorderno"]=$v["order_no"];
               $lists[$k]=$v;
           }
        }
        return json(['code' => 1, 'data' => $lists]);
    }

    //经销商给下级发货明细
    public function jxs_fahuo_detail(){
        $jxs_code = $this->request->param('jxs_code');
        $page= $this->request->param('page',1);
        $size= $this->request->param('size',5);       
        $curr_role=$this->request->param('role');
        $roles=[1,4,5,6,7];
        if(!in_array($curr_role,$roles)){
             return json(['code' => 0, 'message' => "用户角色不存在"]);
        }
        if($curr_role == 1){
           $wh["jxs_code"]=$jxs_code;
           //查询经销商所有的签收单，统计箱码和罐码数量
           $snorder=Db::connect($this->storeconn)->name($this->deliveryorder_sn)->where("jxs_code",$jxs_code)->order("id desc")->select();
           foreach($snorder as $k=>$va){
                $sncode=$va["total_count"];//罐码数量
                $boxcode=$va["total_boxcode"];//箱码数量
                $whfa["deliveryorderno"]=$va["deliveryorderno"];
                $whfa["jxs_code"]=$va["jxs_code"];
                $yifa=Db::connect($this->storeconn)->name($this->deliveryorder_fahuo)->where($whfa)->field("sum(boxcode) as boxcode,sum(sncode) as sncode")->find();
                $va["yifa"]=$yifa;
                $shenyu["boxcode"]=$boxcode;
                $shenyu["sncode"]=$sncode;
                //判断剩余箱数
                if($yifa["boxcode"]){
                    $shenyu["boxcode"]=$boxcode-$yifa["boxcode"];
                }
                if($yifa["sncode"]){
                    $sncode["sncode"]=$sncode-$yifa["sncode"];
                }
                $va["shenyu"]=$shenyu;
                $snorder[$k]=$va;
           }
           return json(['code' => 1, 'data' => $snorder]);  

        }else{
           $wh["wdbh"]=$jxs_code;
           $wh["is_qianshou"]=1;
           $lists=Db::connect($this->storeconn)->name($this->deliveryorder_fahuo)->where($wh)->page($page)->limit($size)->order("id desc")->select();
           foreach($lists as $k=>$v){
                $v["total_boxcode"]=$v["boxcode"];
                $v["total_count"]=$v["sncode"];

                $whfa["deliveryorderno"]=$v["deliveryorderno"];
                $whfa["jxs_code"]=$v["wdbh"];
                $yifa=Db::connect($this->storeconn)->name($this->deliveryorder_fahuo)->where($whfa)->field("sum(boxcode) as boxcode,sum(sncode) as sncode")->find();
                $v["yifa"]=$yifa;
                $shenyu["boxcode"]=$v["boxcode"];
                $shenyu["sncode"]=$v["sncode"];
                //判断剩余箱数
                if($yifa["boxcode"]){
                    $shenyu["boxcode"]=$v["boxcode"]-$yifa["boxcode"];
                }
                if($yifa["sncode"]){
                    $sncode["sncode"]=$v["sncode"]-$yifa["sncode"];
                }
                $v["shenyu"]=$shenyu;
                $lists[$k]=$v;
           }
        }
        
        return json(['code' => 1, 'data' => $lists]);
    }
    
    //经销商及网点库存明细（产品批次，产品名称，产品料号）   实时计算的方法 
    public function jxs_product_kucun_detail(){
        $jxs_code = $this->request->param('jxs_code');
        $page= $this->request->param('page',1);
        $size= $this->request->param('size',5); 
        
        $goodscode= $this->request->param('goodscode',"");
        $goodsname= $this->request->param('goodsname',"");  
        
        $curr_role=$this->request->param('role');
        $roles=[1,4,5,6,7];
        if(!in_array($curr_role,$roles)){
             return json(['code' => 0, 'message' => "用户角色不存在"]);
        }
        if($curr_role == 1){
           $wh["jxs_code"]=$jxs_code;
           //查询经销商所有的签收单，统计箱码和罐码数量
           $snorder=Db::connect($this->storeconn)->name($this->deliveryorder_sn)->where("jxs_code",$jxs_code)->order("id desc")->select();
           $attrdata=[];$ProductCD=[];$productlists=[];
           //1、循环获取签收单中品项
           foreach($snorder as $k=>$va){
                $dethwe["order_no"]=$va["deliveryorderno"];
                $productlist=Db::connect($this->storeconn)
                ->name($this->order_detail)
                ->where($dethwe)
                ->group("productcd")
                ->select();
                foreach ($productlist as $kak=>$vva){ array_push($productlists,$vva);  }
           }

           //获取经销商下级网点
            $wdlist=Db::connect($this->storeconn)->name($this->wx_bos)
            ->where("dealercode",$jxs_code)
            ->where("parent_netcode",null)
            ->order("id desc")
            ->column("netcode");
            
           
           foreach ($productlists as $k=>$v){
               //查询料号中有多少个批次
               $dethwe2["order_no"]=$v["order_no"];
               $dethwe2["productcd"]=$v["productcd"];
               $pic=Db::connect($this->storeconn)
               ->name($this->order_detail)
               ->where($dethwe2)
               ->group("batchno")
               ->select();
                //循环批次获取每个批次的数量
                foreach($pic as $y=>$t){
                    $dethwe3["order_no"]=$v["order_no"];
                    $dethwe3["productcd"]=$v["productcd"];
                    $dethwe3["batchno"]=$t["batchno"];
                    $piccount=Db::connect($this->storeconn)
                    ->name($this->order_detail)
                    ->where($dethwe3)
                    ->select();
                    //循环每条数据判断是否已经下发 code_type 2箱码 1罐码
                    foreach ($piccount as $ku=>$gh){
                        if($gh["code_type"] == 2){
                            //排除已经发货的数据
                            $sc=Db::connect($this->storeconn)
                              ->name($this->deliveryorder_wdfahuo)
                              ->where("boxcode",$gh["code"])
                              ->count();
                            if($sc){ unset($piccount[$ku]); }
                        }else if($gh["code_type"] == 1){
                            $sc=Db::connect($this->storeconn)
                              ->name($this->deliveryorder_wdfahuo)
                              ->where("sncode",$gh["code"])
                              ->count();
                            if($sc){ unset($piccount[$ku]); }
                        }
                    }
                    $piccount=array_values($piccount);
                    $t["pici_count"]=count($piccount);
                    $t["pic_select"]=$piccount;
                    $pic[$y]=$t;
               }
                $v["pic"]=$pic;
                if($goodscode || $goodsname){
                    if($goodscode && $goodsname){
                        if (strstr($v["productcd"], $goodscode) && strstr($v["product_name"], $goodsname)) { $productlists[$k]=$v;continue;}
                        else{  unset($productlists[$k]);}
                    }else{
                        if($goodscode){
                            if (strstr($v["productcd"], $goodscode)) { $productlists[$k]=$v;continue;}
                            else{  unset($productlists[$k]); }
                        }
                        if($goodsname){
                            if (strstr($v["product_name"], $goodsname)) {  $productlists[$k]=$v; continue;}
                            else{  unset($productlists[$k]);}
                        }
                    }
                }else{ $productlists[$k]=$v;  }
                
                if(empty($v["pic"])){ unset($productlists[$k]); continue;}
           }
           $productlists=array_values($productlists);
           return json(['code' => 1, 'data' => $productlists]);

        }else{
           //查询网点的签收单数据
           //1、获取签收单中所有的品项
           $wh["wdbh"]=$jxs_code;
           //$wh["is_qianshou"]=1;
           $ordernos=Db::connect($this->storeconn)->name($this->deliveryorder_fahuo)->where($wh)->column("order_no");
           //2、获取该网点的所有的发货单单号，然再按品项进行分组，获取品项列表
           $lists=Db::connect($this->storeconn)->name($this->deliveryorder_wdfahuo)->where("order_no","in",$ordernos)->group("product_code")->select();
           //获取网下级网点
           $wdlist=Db::connect($this->storeconn)->name($this->wx_bos)
            ->where("parent_netcode",$jxs_code)
            ->order("id desc")
            ->column("netcode");
            
          
           
           foreach($lists as $k=>$v){
                //获取产品的批次信息,循环批次统计每个批次多少
                $ss["product_code"]=$v["product_code"];
                $ss["wdbh"]=$v["wdbh"];
                $ada=Db::connect($this->storeconn)->name($this->deliveryorder_wdfahuo)->where($ss)->group("batch")->select();
                
                //循环每个批次进行统计
                foreach($ada as $yy=>$rr){
                    //根据批次和料号订单号查询是否在下级中出现
                    $dethwe3["order_no"]=$v["order_no"];
                    $dethwe3["product_code"]=$v["product_code"];
                    $dethwe3["batch"]=$rr["batch"];
                    $piccount=Db::connect($this->storeconn)
                    ->name($this->deliveryorder_wdfahuo)
                    ->where($dethwe3)
                    ->select();
                    
                    //循环每条数据判断是否已经下发 code_type 2箱码 1罐码
                    foreach ($piccount as $ku=>$gh){
                        $sc=Db::connect($this->storeconn)
                              ->name($this->deliveryorder_wdfahuo)
                              ->where("wdbh","in",$wdlist)
                              ->where("sncode",$gh["sncode"])
                              ->count();
                       
                        if($sc){ unset($piccount[$ku]); }
                    }
                    
                    $piccount=array_values($piccount);
                    $nrr["pici_count"]=count($piccount);
                    $nrr["pic_select"]=$piccount;//发货明细
                    $ss["batch"]=$rr["batch"];
                    $nrr["norm"]=$rr["product_size"];
                    $nrr["batchno"]=$rr["batch"];
                    $nrr["code_type"]=1;
                    if(empty($nrr["pici_count"])){ unset($ada[$yy]); continue;}
                    
                    $ada[$yy]=$nrr;
                }
                
                if(empty($ada)){ unset($lists[$k]); continue;}
                
                
                $vr["pic"]=$ada;
                $vr["productcd"]=$v["product_code"];
                $vr["product_name"]=$v["product_name"];
                
                if($goodscode || $goodsname){
                    if($goodscode && $goodsname){
                        if (strstr($vr["productcd"], $goodscode) && strstr($vr["product_name"], $goodsname)) { $lists[$k]=$vr;continue;}
                        else{  unset($lists[$k]);}
                    }else{
                        if($goodscode){
                           if (strstr($vr["productcd"], $goodscode)) {  $lists[$k]=$vr; continue; }
                           else{ unset($lists[$k]); }
                        }
                        if($goodsname){
                            if (strstr($vr["product_name"], $goodsname)) { $lists[$k]=$vr; continue;}
                            else{ unset($lists[$k]); }
                        }
                    }
                }else{ $lists[$k]=$vr; }
           }
        }
        $lists=array_values($lists);
        return json(['code' => 1, 'data' => $lists]);
    }
    
    //新库存明细，走的库存表数据
    public function jxs_product_kucun_detail_new(){
        $user_id = $this->request->param('user_id');
        $page= $this->request->param('page',1);
        $size= $this->request->param('size',5);
        $lists=[];
        $wdinfo=Db::name($this->wx_bos)->where("id",$user_id)->find();
        if($user_id == 24){
            $lists=Db::name("product_kucun")->field("product_code as ProductCD,product_name as ProductName,sn_count")
            ->where("jxs_code","20241129003")->select();
        }else{
            if($wdinfo){
                $lists2=Db::name("deliveryorder_fahuo_detail")
                ->where(["wdbh"=>$wdinfo["user_code"],"is_send"=>0])
                ->field("id,count(1) as sn_count,product_code as ProductCD, product_name as ProductName")
                ->group("product_code")
                ->select();

                $lists=Db::name("jxs_kucun")
                ->where(["jxs_code"=>$wdinfo["user_code"],"is_send"=>0])
                ->field("*,count(1) as sn_count")
                ->group("ProductCD")
                ->select();
            }
        }
        return json(['code' =>200, 'data' => $lists]);
    }
    
    //出库单明细
    public function jxs_product_kucun_chukulog(){
         $jxs_code = $this->request->param('jxs_code');
        $page= $this->request->param('page',1);
        $size= $this->request->param('size',5);
        $goodscode= $this->request->param('goodscode',"");
        $goodsname= $this->request->param('goodsname',"");
        $curr_role=$this->request->param('role');
       
        $hwer["jxs_code"]=$jxs_code;
        $hwers=[];
        if($goodscode){
            $hwers[]=['product_code',"like",'%'.$goodscode."%"];
        }
        if($goodsname){
            $hwers[]=["product_name","like",'%'.$goodsname."%"];
        }
        //$accp_product_arr=get_duoqu_product_show();
        $lists=[];
        $lists=Db::name("deliveryorder_fahuo")->where($hwer)->where($hwers)->order("id desc")->select();
        foreach($lists as $kk=>$val){
             $val["detail"]=Db::name("deliveryorder_fahuo_detail")->where("order_no",$val["order_no"])
             ->group("product_code")->field("product_code,product_name,count(1) as count")->select();
             $lists[$kk]=$val;
        }
        return json(['code' => 200, 'data' => $lists]);
        
    }
  
    //查询箱码是否已经发货
    public function check_boxcode_vail(){
        $boxcode = $this->request->param('boxcode');
        $jxs_code = $this->request->param('jxs_code');
        $wdbh= $this->request->param('wdbh');
        $aht=substr($boxcode,0,20);
        if($aht=="http://weixin.qq.com"){
             return xcx_error("请遮住下方的官网二维码之后再扫");
        }
        if($aht=="https://myr.wissun.n"){
            return xcx_error("该扫的码无效");
        }
        $wdbh=trim($wdbh);
        $wxbox=Db::name($this->wx_bos)->where("user_code",$wdbh)->find();
        if($wxbox){
            $jxsinfo=Db::name($this->wx_bos)->where("user_code",$jxs_code)->find();
            if($jxsinfo["role"]){
                if($wxbox["parent_id"] != $jxsinfo["id"]){
                     return json(['code' => 1, 'message' =>$wdbh."网点与经销商不匹配~"]);
                }    
            }else{
                if($wxbox["parent_id"] != 24){
                     return json(['code' => 1, 'message' =>"经销商不是顶级"]);
                }
            }
        }else{
            return json(['code' => 1, 'message' =>"未找到".$wdbh."网点信息~" ]);
        }
        
        
        
        $insert["boxcode"]=$boxcode;
        $insert["jxs_code"]=$jxs_code;
        $insert["add_time"]=date("Y-m-d H:i:s");        
        //罐码判断
        if(strlen($boxcode) == 53){
            //罐底码，逻辑是罐底码查询箱码，箱码查询出货单，出货单查询经销商信息
            $http=substr($boxcode,0,4);
            if($http == "http"){
                $boxcode=substr($boxcode,33);
                //只允许配置中的产品进行扫码
                $vcodes=Db::connect($this->erpdb)->name("v_code")->where("TrackCode",$boxcode)->find();
                $pconfig=Db::name("jxs_product_config")->where("product_code",$vcodes["ProductCD"])->where("status",1)->find();
                if($pconfig){
                    if($pconfig["batch"]){
                        $batchno="";
                        if(strlen($vcodes["BatchNO"]) == 8){
                            $batchno=$vcodes["BatchNO"];
                        }else {
                            $batchno="20".substr($vcodes["BatchNO"],0,6);
                        }
                        if($batchno < $pconfig["batch"]){
                            return json(['code' => 1, 'message' =>"该品项不允许扫码发货~" ]);
                        }
                    }
                }
                
                if($jxs_code == "20241129003"){ //国代用户，根据出货单的库存去控制库存
                     //判断用户的库存是否足够
                    $mpmy["product_code"]=$vcodes["ProductCD"];
                    $mpmy["batchno"]=$vcodes["BatchNO"];
                    $mpmy["jxs_code"]=$jxs_code;
                    $is_ex=Db::name("product_kucun")->where($mpmy)->find();
                    if(empty($is_ex)){
                        return json(['code' => 1, 'message' =>"产品未入库~" ]);
                    }
                    if($is_ex["sn_count"] <= 0){
                        return json(['code' => 1, 'message' =>"库存不足!" ]);
                    }
                }
                $iszaiku=Db::name("jxs_kucun")->where(["sncode"=>$boxcode,"jxs_code"=>$jxsinfo["user_code"]])->where("is_send","<",2)->order("id desc")->find();
                if($iszaiku){
                    if($iszaiku["is_send"]){
                        return json(['code' => 1, 'message' =>"该罐已经下发了~" ]);
                    }
                }else{
                    return json(['code' => 1, 'message' =>"该罐不属于您~" ]);
                }
                $isec["ptype"]=1;
                return json(['code' => 200, 'message' =>"罐码有效","data"=>$boxcode,"type"=>1,"showdata"=>$isec]);
            }
        }
        else{
            $attr=substr($boxcode,0,5);
            if($attr == "12345"){ $boxcode=substr($boxcode,5);  }
            //只允许配置中的产品进行扫码
            $vcodes=Db::connect($this->erpdb)->name("v_code")->where("BoxCode",$boxcode)->find();
            $pconfig=Db::name("jxs_product_config")->where("product_code",$vcodes["ProductCD"])->where("status",1)->find();
            if($pconfig){
                if($pconfig["batch"]){
                    $batchno="";
                    if(strlen($vcodes["BatchNO"]) == 8){
                        $batchno=$vcodes["BatchNO"];
                    }else {
                        $batchno="20".substr($vcodes["BatchNO"],0,6);
                    }
                    if($batchno < $pconfig["batch"]){
                        return json(['code' => 1, 'message' =>"该品项不允许扫码发货~" ]);
                    }
                }
            }
            if($jxs_code == "20241129003"){ //国代用户，根据出货单的库存去控制库存
                 //判断用户的库存是否足够
                $mpmy["product_code"]=$vcodes["ProductCD"];
                $mpmy["batchno"]=$vcodes["BatchNO"];
                $mpmy["jxs_code"]=$jxs_code;
                $is_ex=Db::name("product_kucun")->where($mpmy)->find();
                if(empty($is_ex)){
                    return json(['code' => 1, 'message' =>"产品未入库~"]);
                }
                if($is_ex["sn_count"] <= 0){
                    return json(['code' => 1, 'message' =>"库存不足~" ]);
                }
            }
            $iszaiku_map["boxcode"]=$boxcode;
            $iszaiku_map["jxs_code"]=$jxsinfo["user_code"];
            //is_send 2 退货
            $iszaiku=Db::name("jxs_kucun")->where($iszaiku_map)->where("is_send","<",2)->order("id desc")->select()->toarray();
            if($iszaiku){
                foreach($iszaiku as $kk=>$vv){
                    if($vv["is_send"]){
                        return json(['code' => 1, 'message' =>"该箱中存在已经下发了的产品~" ]);
                    }
                }
            }else{
                return json(['code' => 1, 'message' =>"该箱不属于您~" ]);
            }
            $isec["ptype"]=1;
            return json(['code' => 200, 'message' =>"箱码有效","data"=>$boxcode,"type"=>2,"showdata"=>$isec]);
            
        }
    }
    
    //经销商下级网点包含网点招募的
    public function get_wddata_lists(){
		$dealercode=input("dealercode");
		$keyword=input("keyword","");
		$corrent_role=input("role","");
		$data=[];
		if(empty($dealercode)){
		     return xcx_error("缺少经销商信息,请重新扫罐底码");
		}
		$corrent_role=explode(",",$corrent_role);
		if(in_array(1,$corrent_role) || in_array(8,$corrent_role)){
	    	$field="netcode,netname,netaddr,dealercode,dealername";
	    	if($keyword){
	    	    $whereOr=[];
	    	    $whereOr[] = [['netcode', 'like',"%".$keyword."%"]];
    			$whereOr[] = [['netname', 'like',"%".$keyword."%"]];
	    	    $data=Db::connect($this->storeconn)->name($this->wx_bos)
    			->where("multidealercode",'like','%'.$dealercode.'%') //多经销商编号
    			->where("parent_netcode",null)
        		->where(function ($query) use($whereOr) { $query->whereOr($whereOr);})
    			->field($field)
    			->order("id desc")
    			->select();
	    	}else{
	    	    $data=Db::connect($this->storeconn)->name($this->wx_bos)
    			->where("multidealercode",'like','%'.$dealercode.'%') //多经销商编号
    			->where("parent_netcode",null)
    			->field($field)
    			->order("id desc")
    			->select();
	    	}
		}else{
		    $field="netcode,netname,netaddr,dealercode,dealername";
		    if($keyword){
	    	    $whereOr=[];
	    	    $whereOr[] = [['netcode', 'like',"%".$keyword."%"]];
    			$whereOr[] = [['netname', 'like',"%".$keyword."%"]];
	    	    $data=Db::connect($this->storeconn)->name($this->wx_bos)
    		    ->where("parent_netcode",$dealercode)
    		    ->where(function ($query) use($whereOr) { $query->whereOr($whereOr);})
    		    ->field($field)
    		    ->select();
	    	}else{
    		    $data=Db::connect($this->storeconn)->name($this->wx_bos)
    		    ->where("parent_netcode",$dealercode)
    		    ->field($field)
    		    ->select();
	    	}
		}
	
	    return xcx_success($data);
	}
	
	//经销商下级网点包含月网点招募统计数据
    public function get_wddata_mouth_lists(){
		$dealercode=input("dealercode");
		$keyword=input("keyword","");
		$corrent_role=input("role","");
		$data=[];
		$corrent_role=explode(",",$corrent_role);
		$mouthdata=Db::connect($this->storeconn)->name("net_shouhuo_data")->where("parent_netcode",$dealercode)
		->field("mouth")->group("mouth")->order("mouth desc")->select();
		foreach($mouthdata as $t=>$row){
		    //$mouth=date("Ym");
		    $mouth=$row["mouth"];
    		$data=Db::connect($this->storeconn)->name("net_shouhuo_data")->where("parent_netcode",$dealercode)
    		->field("*,sum(total) as total")->where("mouth",$mouth)->group("netcode")->order("id desc")->select();
    		foreach($data as $kk=>$val){
    		    $detail=Db::connect($this->storeconn)->name("net_shouhuo_data")->where("parent_netcode",$dealercode)
    		    ->where("mouth",$mouth)
    		    ->where("netcode",$val["netcode"])
    		    ->group("product_code")
    		    ->order("id desc")
    		    ->select();
    		    $val["detail"]=$detail;
    		    $data[$kk]=$val;
    		}
    		$row["data"]=$data;
    		$mouthdata[$t]=$row;
		}
	    return xcx_success($mouthdata);
	}
	
	//经销商下级网点包含月6兑1
    public function get_mouth_liuduiyi(){
		$dealercode=input("dealercode");
		$keyword=input("keyword","");
		$corrent_role=input("role","");
		$data=[];
		$corrent_role=explode(",",$corrent_role);
		$mouthdata=Db::connect($this->storeconn)->name("net_6to1_data")->where("parent_netcode",$dealercode)
		->field("mouth")->group("mouth")->order("mouth desc")->select();
		foreach($mouthdata as $t=>$row){
		    //$mouth=date("Ym");
		    $mouth=$row["mouth"];
    		$data=Db::connect($this->storeconn)->name("net_6to1_data")->where("parent_netcode",$dealercode)
    		->field("*,sum(total) as total")->where("mouth",$mouth)->group("netcode")->order("id desc")->select();
    		foreach($data as $kk=>$val){
    		    $detail=Db::connect($this->storeconn)->name("net_6to1_data")->where("parent_netcode",$dealercode)
    		    ->where("mouth",$mouth)
    		    ->where("netcode",$val["netcode"])
    		    ->group("product_code")
    		    ->order("id desc")
    		    ->select();
    		    $val["detail"]=$detail;
    		    $data[$kk]=$val;
    		}
    		$row["data"]=$data;
    		$mouthdata[$t]=$row;
		}
	    return xcx_success($mouthdata);
	}
	
	//整箱和零售一起发送，整合一起-给下级发货
    public function product_fahuo_wd(){
        $param = $this->request->param();
        $jxs_code = $this->request->param('jxs_code');
        $jxs_name = $this->request->param('jxs_name');
        $wdbh_name=$this->request->param('wdbh_name');
        $role = $this->request->param('role');
        $validate = new Validate([
            'wdbh' => 'require',
            'jxs_code'=>'require'
        ]);
        $check_res = $validate->check($param);
        if (!$check_res) {
            return json(['code' => 1, 'message' => $validate->getError()]);
        }
        $boxcodelist= $this->request->param('boxcodelist');//接收箱码集
        $sncodelist= $this->request->param('sncodelist');//接收罐码集
        $insert["custcode"]=$jxs_code;
        $wdbh=$param["wdbh"];

        $wdinfo=Db::name($this->wx_bos)->where("user_code",$wdbh)->find();
        if(empty($wdinfo)){
            return json(['code' => 1, 'message' => "网点信息不存在"]);
        }
        $is_qianshou=0;
        Db::startTrans();
        $facode["order_no"]="W".time().mt_rand(10,99);
        $xminfo=[];//箱码信息
        $TrackCode=[];
		if($boxcodelist){
            $boxcodelist=explode(",",$boxcodelist);
            $message="";
            foreach($boxcodelist as $kk=>$boxcode){
                $productlist=Db::connect($this->erpdb)->name("v_code")->where("BoxCode",$boxcode)->select();
                foreach($productlist as $key=>$vv){
                    array_push($TrackCode,$vv["TrackCode"]);
                    array_push($xminfo,$vv);
                }
            }
		}
		if($sncodelist){
		    $sncodelist=explode(",",$sncodelist);
            foreach($sncodelist as $k=>$sncode){
                if(!in_array($sncode,$TrackCode)){
                    array_push($TrackCode,$sncode);
                    $vvass=Db::connect($this->erpdb)->name("v_code")->where("TrackCode",$sncode)->find();
                    array_push($xminfo,$vvass);
                }
            }
		}
		if($xminfo){
            $facode["sncode"]=count($xminfo);
            foreach($xminfo as $k=>$sncode){
                $insertall["wdbh"]=$wdbh;
                $insertall["wd_name"]=$wdbh_name;
                $insertall["count"]=1;
                $insertall["order_no"]=$facode["order_no"];
                $insertall["add_time"]=time();
                $insertall["boxcode"]=$sncode["BoxCode"];
                $insertall["product_code"]=$sncode["ProductCD"];
                $insertall["product_name"]=$sncode["ProductName"];
                $insertall["sncode"]=$sncode["TrackCode"];
                $insertall["custcode"]=$jxs_code;
                $insertall["custname"]=$jxs_name;
                $insertall["is_qianshou"]=$is_qianshou;//是否签收
                $insertall["product_size"]=$sncode["Norm"];
                $insertall["batch"]=$sncode["BatchNO"];
                if($is_qianshou){
                    $insertall["qs_time"]=time();
                }
                $result=Db::name("deliveryorder_fahuo_detail")->insert($insertall);//加入给网点发货的记录表
                //减少用户库存表中数量
                $uuwhere["product_code"]=$sncode["ProductCD"];
                $uuwhere["batchno"]=$sncode["BatchNO"];
                $uuwhere["jxs_code"]=$jxs_code;
                Db::name("product_kucun")->where($uuwhere)->dec("sn_count",1)->update();//减少对应的库存
                if($jxs_code == "20241129003"){
                    $newkucun=Db::name("product_kucun")->where($uuwhere)->value("sn_count");
                    if(empty($newkucun)){
                        Db::rollback();
                        return json(['code' => 1, 'message' => "产品未入库~"]);
                    }else if($newkucun <= 0){
                        Db::rollback();
                        return json(['code' => 1, 'message' => "库存不足~~"]);
                    }
                }
                $uuwhere3["custcode"]=$jxs_code;
                $uuwhere3["sncode"]=$sncode;
                $uuwhere3["is_send"]=0;
                Db::name("deliveryorder_fahuo_detail")->where($uuwhere3)->update(["is_send"=>1]);//修改库存数据的状态

                $uuwhere2["jxs_code"]=$jxs_code;
                $uuwhere2["sncode"]=$sncode;
                $uuwhere2["is_send"]=0;
                Db::name("jxs_kucun")->where($uuwhere2)->update(["is_send"=>1]);//修改库存数据的状态
                if($is_qianshou){
                    $uuwhere3["product_code"]=$sncode["ProductCD"];
                    $uuwhere3["batchno"]=$sncode["BatchNO"];
                    $uuwhere3["jxs_code"]=$wdbh;
                    $isc=Db::name("product_kucun")->where($uuwhere3)->find();
                    if($isc){
                        Db::name("product_kucun")->where($uuwhere3)->inc("sn_count",1)->update();
                    }else{
                        $instkuc["jxs_code"]=$wdbh;
                        $instkuc["product_code"]=$sncode["ProductCD"];
                        $instkuc["product_name"]=$sncode["ProductName"];
                        $instkuc["product_size"]=$sncode["Norm"];
                        $instkuc["batchno"]=$sncode["BatchNO"];
                        $instkuc["count"]=0;
                        $instkuc["sn_count"]=1;
                        $instkuc["type"]=1;
                        Db::name("product_kucun")->insert($instkuc);
                    }
                    $sjxskucun["sncode"]=$sncode["TrackCode"];
                    $sjxskucun["jxs_code"]=$wdbh;
                    $sjxskucun["boxcode"]=$sncode["BoxCode"];
                    $sjxskucun["is_send"]=0;
                    $sjxskucun["add_time"]=date("Y-m-d H:i:s");
                    Db::name("jxs_kucun")->insert($sjxskucun);
                }
            }
		}
        //新增下级出货单
        $facode["add_time"]=date("Y-m-d H:i:s");
        if($is_qianshou){
            $facode["qs_time"]=time();
        }
        $facode["wdbh"]=$wdbh;
        $facode["wdbh_name"]=$wdbh_name;
        $facode["boxcode"]=0;//箱数
        $facode["jxs_code"]=$jxs_code;//上级用户
        $facode["is_qianshou"]=$is_qianshou;//是否签收
        $resc=Db::name("deliveryorder_fahuo")->insertGetId($facode);
        if($resc){
            Db::commit();
            return json(['code' => 200, 'message' =>"发货操作成功" ,'data'=>$facode,'resc'=>$resc]);
        }else{
            Db::rollback();
        }
	    return json(['code' => 1, 'message' =>"发货操作失败" ]);
    }

	//查询产品信息
    public function select_product_info(){
        $boxcode=input("boxcode","");
        $type=input("type",1);
        if($type == 1){
            $product= Db::connect($this->erpdb)->name("v_code")->where("TrackCode",$boxcode)->find();
        }else{
            $product= Db::connect($this->erpdb)->name("v_code")->where("BoxCode",$boxcode)->find();
        }
        return json(['code' => 0, 'data' => $product]);
    }

    
    public function ocryingye(){
        $orc = $this->request->param('orc',"https://ayh.wissun.net/Uploads/xklb/2024-07-11/3bd2b7d2540a77294545edc83ecc5d9b.png");
        $jxs_code = $this->request->param('jxs_code');
        $accessKeyId = $this->access_key_id;
    }
    
    public function check_wdcode_use(){
        $param = $this->request->param();
        $where["netcode"]=$param["netcode"];
        $isexit=Db::connect($this->storeconn)->name($this->wx_bos)->where($where)->find();
        if($isexit){
            return json(['code' => 1, 'message' =>"网点已经认证了，请勿重复认证~"]);
        }
        return json(['code' => 0, 'message' =>"ok~"]);
    }
    
    //保存网点信息（网点招募）-废弃
    public function save_wd_info(){
        $param = $this->request->param();
        $validate = new Validate([
            'ying_ye_zhi_zao' => 'require',
            'netname' => 'require',
            'bossphone' => 'require',
            'netaddr' => 'require',
            'role'    => 'require',
            'jxs_code' => 'require',
            'nickname' => 'require',
            'yyzz_pic' => 'require'
        ]);
        $check_res = $validate->check($param);
        if (!$check_res) {
            return json(['code' => 1, 'message' => $validate->getError()]);
        }
        if(!isset($param["netname2"])){
            $param["netname2"]=$param["netname"];
        }
        // $where["netname"]=$param["netname"];
        // $isexit=Db::connect($this->storeconn)->name($this->wx_bos)->where($where)->find();
        // if($isexit){
        //     return json(['code' => 1, 'message' =>"网点名称已存在~"]);
        // }
        
        $whe["ying_ye_zhi_zao"]=$param["ying_ye_zhi_zao"];
        $isexit=Db::name($this->wx_bos)->where($whe)->find();
        if($isexit){
            return json(['code' => 1, 'message' =>"营业执照编号已存在！"]);
        }
        
        $issys=Db::name("system_user")->where("username",trim($param["bossphone"]))->find();
        $insert["openid"]=$param["openid"];
        $insert["netname"]=($param["netname"] == "暂无")?$param["netname2"]:$param["netname"];
        $insert["netname2"]=$param["netname2"];
        $insert["ying_ye_zhi_zao"]=$param["ying_ye_zhi_zao"];
        $insert["bossphone"]=$param["bossphone"];
        $insert["netaddr"]=$param["netaddr"];
        $insert["product"]=$param["product"];
        
        $role=explode(",",$param["role"]);
        if(in_array(1,$role)){
            $insert["dealername"]=$param["nickname"];
            $insert["dealercode"]=$param["jxs_code"];
            $insert["multidealercode"]=$param["jxs_code"];
        }else{
            //网点新增网点的情况下
            $wxwhere["netcode"]=$param["jxs_code"];
            $product=Db::name($this->wx_bos)->where($wxwhere)->find();
            $insert["dealername"]=$product["dealername"];
            $insert["dealercode"]=$product["dealercode"];
            $insert["multidealercode"]=$product["dealercode"];
            $insert["parent_netcode"]=$product["netcode"];
            $insert["parent_name"]=$product["netname"];
        }
        $curr_user_code=Db::name($this->wx_bos)->where("user_code","like","%".date("Ymd")."%")->order("user_code desc")->value("user_code");
        if($curr_user_code){
            $netcode=$curr_user_code+1;
        }else{
            $netcode=date("Ymd")."001";
        }
        $insert["netcode"]=$netcode;
        $insert["wdstatus"]= 0;//网点状态
        $insert["set_account_time"]=date("Y-m-d H:i:s");
        $insert["yyzz_pic"]= $param["yyzz_pic"];//营业执照图片
        $whe22["ying_ye_zhi_zao"]=$param["ying_ye_zhi_zao"];
        $isexit2=Db::name($this->wx_bos)->where($whe22)->find();
        if($isexit2){
            if(empty($isexit2["multidealercode"])){
                $isexit2["multidealercode"]=$isexit2["dealercode"];
            }
            $multidealercode=explode(",",$isexit2["multidealercode"]);
            array_push($multidealercode,$insert["dealercode"]);
            $updates["multidealercode"]=implode(",",$multidealercode);
            $rras=Db::name($this->wx_bos)->where("id",$isexit2["id"])->update($updates);
            if($rras){
                return json(['code' => 1, 'message' =>"共享网点认证成功,账号和密码保持不变~"]);
            }else{
                return json(['code' => 1, 'message' =>"提交网点失败~~"]);
            }
        }
        
        $result=Db::name($this->wx_bos)->insert($insert);
        if($result){
            if(empty($issys)){
               $sysuser["username"]=$param["bossphone"];//用户账号
                $sysuser["password"]=md5(123456);//用户账号
                $sysuser["nickname"]=($param["netname"] == "暂无")?$param["netname2"]:$param["netname"];//用户昵称
                $sysuser["contact_phone"]=$param["bossphone"];//联系手机
                $sysuser["authorize"]="4";
                $sysuser["contact_jxscode"]=$insert["netcode"];
                Db::name("system_user")->insert($sysuser);
            }
            return json(['code' => 0, 'message' =>"提交网点信息成功~"]);
        }else{
            return json(['code' => 1, 'message' =>"提交网点失败~"]);
        }
    }
    
    //查询经销商经营品项
    public function jxs_product_code(){
        $param = $this->request->param();
        $validate = new Validate([
            'jxs_code' => 'require',
            'role' => 'require'
        ]);
        $check_res = $validate->check($param);
        if (!$check_res) {
            return json(['code' => 1, 'message' => $validate->getError()]);
        }
        $role=explode(",",$param["role"]);
        if(in_array(1,$role)){
            //经销商经营品项
            $product=Db::connect($this->erpdb)->name("localtcqssfile")->where("tc_qss01",$param["jxs_code"])->select();
        }else{
            //网点新增网点的情况下，只能从网点中经营品项中选择经营品项
            $wxwhere["netcode"]=$param["jxs_code"];
            $product=Db::connect($this->storeconn)->name($this->wx_bos)->where($wxwhere)->find();
            $newwhere["tc_qss01"]=$product["dealercode"];
            $product=Db::connect($this->erpdb)->name("localtcqssfile")
            ->where("tc_qss04","in",$product["product"])->where($newwhere)
            ->select();
        }
        return json(['code' => 0, 'message' =>"success","data"=>$product]);
        
    }
    
    //发货溯源
    public function fa_huo_shuyuan(){
        $wdbh = $this->request->param('wdbh');
        $wdname = $this->request->param('wdname');
        $date= $this->request->param('date');
        $boxcode= $this->request->param('boxcode');
        $sncode= $this->request->param('sncode');
        $page= $this->request->param('page');
        $size= $this->request->param('size');
		$jxs_code= $this->request->param('jxs_code');

	    $where=[];
	    $where[]=["custcode","=",$jxs_code];
        if($date){
            $where[]=["add_time",">=",strtotime($date." 00:00:00")];
			$where[]=["add_time","<=",strtotime($date." 23:59:59")];
        }

	    $result=Db::name("deliveryorder_fahuo_detail")
        ->where($where)
        ->where(function ($query) use ($sncode) {
             if($sncode){
                $len = strlen($sncode);  // 获取字符串的长度
                if ($len >= 6) {  // 确保字符串长度大于等于 6
                    $type = substr($sncode, -6, 1);
                    if($type == 1){
                        $query->where("sncode","like",'%'.$sncode.'%');
                    }else if($type == 2){
                        $query->where("boxcode","like",'%'.$sncode.'%');
                    }
                }
             }
         })
        ->page($page)
        ->limit($size)
        ->order('id desc')
        ->select();
        
        return json(['code' => 200, 'data' => $result]);
    }

    //撤销发货
    public function chexiao_fahuo(){
        $order_no = $this->request->param('order_no');
        $fahuo=Db::name("deliveryorder_fahuo")->where("order_no",$order_no)->find();
         
        if($fahuo){
            if($fahuo["is_qianshou"] == 1){
               return json(['code' => 200,"data"=>["code"=>1,"message"=>"发货单已签收，无法撤销~"]]);
            }
            $parent_jxs=$fahuo["jxs_code"];//上级经销商
            $wdbh=$fahuo["wdbh"];//接收网点
            Db::startTrans();
            $detail=Db::name("deliveryorder_fahuo_detail")->where("order_no",$fahuo["order_no"])->select();
            foreach($detail as $kk=>$val){
                $map["sncode"]=$val["sncode"];
                $map["jxs_code"]=$parent_jxs;
                $map["is_send"]=1;
                $update["is_send"]=0;
                $res=Db::name("jxs_kucun")->where($map)->update($update);

                //增加库存
                if($parent_jxs == "20241129003"){
                    $kwhere["jxs_code"]=$parent_jxs;
                    $kwhere["product_code"]=$val["product_code"];
                    $kwhere["batchno"]=$val["batch"];
                    Db::name("product_kucun")->where($kwhere)->inc("sn_count",1)->update();
                }
                Db::name("deliveryorder_fahuo_detail")->where("id",$val["id"])->delete();
            }
            Db::name("deliveryorder_fahuo")->where("id",$fahuo["id"])->delete();
            Db::commit();
           return json(['code' => 200,"data"=>["code"=>2,"message"=>"撤销成功~"]]);
        }

    }

    //识别营业执照的内容
    public function shibie_yyzz(){
        ini_set('memory_limit', '256M');
        // 替换成你的Access Key ID和Access Key Secret
        $pic=input("pic","");
        if(empty($pic)){
            return json(['code' => 0,"message"=>"参数不能为空"]);
        }
        $accessKeyId = 'LTAI5t6HbthecH3XZWZfaWY1';
        $accessKeySecret = 'ZM7YMKpDiXnO6S3F69UgtPsNepNPyu';
        $config = new Config([
            "accessKeyId" => $accessKeyId,
            "accessKeySecret" => $accessKeySecret
        ]);
        $config->endpoint = "ocr-api.cn-hangzhou.aliyuncs.com";
        $client = new OpenApiClient($config);
        $params = new Params([
            // 接口名称
            "action" => "RecognizeBusinessLicense",
            // 接口版本
            "version" => "2021-07-07",
            // 接口协议
            "protocol" => "HTTPS",
            // 接口 HTTP 方法
            "method" => "POST",
            "authType" => "AK",
            "style" => "V3",
            // 接口 PATH
            "pathname" => "/",
            // 接口请求体内容格式
            "reqBodyType" => "json",
            // 接口响应体内容格式
            "bodyType" => "json"
        ]);
        $pic=str_replace("https://ayh.wissun.net/","",$pic);
        $bodyStream = StreamUtil::readFromFilePath($pic);
        $runtime = new RuntimeOptions([]);
        $request = new OpenApiRequest([
            "stream" => $bodyStream
        ]);
        $result = $client->callApi($params, $request, $runtime);
        trace("识别结果",json_encode($result,JSON_UNESCAPED_UNICODE));
        return json(['code' => 1, 'data' => $result]);
    }

    //获取网点信息
    public function get_wxbox_info(){
        $jxs_code = $this->request->param('jxs_code');
        $role = $this->request->param('role');
        $where["wdbh"]=$jxs_code;
        $role=explode(",",$role);
        $result=[];
        if(in_array(8,$role)){
             $result=Db::connect($this->storeconn)->name($this->wx_bos)->field("city,county,province,latitude,longitude")->where($where)->find();
        }else  if(in_array(1,$role)){
            $result["latitude"]="39.984060";
            $result["longitude"]="116.307520";
        }
        return json(['code' => 1, 'data' => $result]);
    }
    
    // 调用OCR API
    function recognizeText($client, $imagePath) {
        $imageBase64 = encodeImage($imagePath);
        $request = createOcrRequest($imageBase64);
        $response = $client->recognizeCharacter($request);
        return $response->toMap();
    }

    //获取产品信息
    public function get_product_info(){
        $boxcode = $this->request->param('code');
        $jxs_code = $this->request->param('jxs_code');
        
        //罐码判断
        if(strlen($boxcode) == 53){
            $http=substr($boxcode,0,4);
            if($http == "http"){
                $boxcode=substr($boxcode,33);
                $isdata=Db::name("jxs_kucun")->where(["jxs_code"=>$jxs_code,"sncode"=>$boxcode,"is_send"=>0])->find();
                if($isdata){
                     $result=Db::connect($this->erpdb)->name("v_code")->where("TrackCode",$boxcode)->select();
                     return json(['code' => 200, 'message' =>"查询成功","data"=>$result,"type"=>1]);
                }else{
                    return json(['code' => 0, 'message' =>"该产品不在您的库存中","type"=>1]);
                }
            }
        }else{
            //箱码
            $attr=substr($boxcode,0,5);
            if($attr == "12345"){ $boxcode=substr($boxcode,5);  }
            $isdata=Db::name("jxs_kucun")->where(["jxs_code"=>$jxs_code,"boxcode"=>$boxcode,"is_send"=>0])->find();
            if($isdata){
                 $result=Db::connect($this->erpdb)->name("v_code")->where("BoxCode",$boxcode)->select();
                 return json(['code' => 200, 'message' =>"查询成功","data"=>$result,"type"=>2]);
            }else{
                return json(['code' => 0, 'message' =>"该产品不在您的库存中","type"=>2]);
            }
        }
    }
    
    //保存退货申请单,经销商申请人员处理，门店退货直接到库存
    public function save_return_apply(){
        $param = $this->request->param();
        $validate = new Validate([
            'jxs_code' => 'require',
            'jxs_name' => 'require',
            'order_no' => 'require',
            'codelist' => 'require',
        ]);
        $check_res = $validate->check($param);
        if (!$check_res) {
            return json(['code' => 0, 'message' => $validate->getError()]);
        }
        $isexit=Db::name("return_apply")->where("order_no",$param["order_no"])->find();
        if($isexit){
           return json(['code' => 0, 'message' => "订单号已经存在,请重新刷新界面"]); 
        }
        Db::startTrans();
        $insert["status"]=0;
        $insert["order_no"]=$param["order_no"];
        $insert["add_time"]=date("Y-m-d H:i:s");
        $insert["uid"]=$param["jxs_code"];
        $insert["uname"]=$param["jxs_name"];
        $newid=Db::name("return_apply")->insertGetId($insert);
        $codelist=json_decode($param["codelist"],true);
        $inall=[];
        foreach ($codelist as $Kk=>$vv){
            $isdata=Db::name("jxs_kucun")->where(["jxs_code"=>$param["jxs_code"],"sncode"=>$vv["TrackCode"],"is_send"=>0])->find();
            if(empty($isdata)){
                return json(['code' => 0, 'message' => $vv["TrackCode"]."该罐不在您的库存中"]); 
            }
            //检测罐码是否已经扫码了，扫码了之后，不允许退货
            $issanma=Db::name("scan_qrcode_log_jinfen")->where(["trace_code"=>$vv["TrackCode"],"status"=>1])->find();
            if($issanma){
                return json(['code' => 0, 'message' => $vv["TrackCode"]."该罐已经开罐扫码了"]); 
            }
            
            $vv["return_id"]=$newid;
            $v["sncode"]=$vv["TrackCode"];
            $v["boxcode"]=$vv["BoxCode"];
            $v["product_code"]=$vv["ProductCD"];
            $v["product_name"]=$vv["ProductName"];
            $v["product_size"]=$vv["Norm"];
            $v["norm"]=$vv["BatchNO"];
            $v["return_id"]=$newid;
            $v["uid"]=$param["jxs_code"];
            $v["uname"]=$param["jxs_name"];
            $v["add_time"]=time();
            $v["return_no"]=$param["order_no"];
            array_push($inall,$v);
            Db::name("jxs_kucun")->where(["jxs_code"=>$param["jxs_code"],"sncode"=>$vv["TrackCode"]])->update(["is_send"=>2]);
            Db::name("product_kucun")->where(["jxs_code"=>$param["jxs_code"],"batchno"=>$vv["BatchNO"],"product_code"=>$vv["ProductCD"]])->dec("sn_count",1)->update();
            
        }
        $result=Db::name("return_apply_detail")->insertAll($inall);
        Db::commit();
        return json(['code' => 200]);
    }
    
    //获取审批记录
    public function apply_log(){
        $param = $this->request->param();
        $validate = new Validate([
            'jxs_code' => 'require',
        ]);
        $check_res = $validate->check($param);
        if (!$check_res) {
            return json(['code' => 0, 'message' => $validate->getError()]);
        }
        
        $datalist=Db::name("return_apply")->where("uid",$param["jxs_code"])->order("id desc")->select();
        foreach ($datalist as $kk=>$val){
            $val["detail"]=Db::name("return_apply_detail")->where("return_id",$val["id"])->select();
            $datalist[$kk]=$val;
        }
        
        return json(['code' => 200,"data"=>$datalist]);
    }
    
    //审核申请记录
    public function shenhe_apply(){
        $param = $this->request->param();
        $validate = new Validate([
            'jxs_code' => 'require',
            'log_id' => 'require',
            'action' => 'require',
        ]);
        $check_res = $validate->check($param);
        if (!$check_res) {
            return json(['code' => 0, 'message' => $validate->getError()]);
        }
        $rruu=Db::name("return_apply")->where("id",$param["log_id"])->find();
        if(empty($rruu)){
            return json(['code' => 0, 'message' => "订单信息不存在"]);
        }
        if($rruu["status"] != 0){
            return json(['code' => 0, 'message' => "订单已处理,勿需在处理"]);
        }
        if($param["action"] == "accept"){
            Db::startTrans();
            $newid=$param["log_id"];
            $detaillist=Db::name("return_apply_detail")->where("return_id",$newid)->select();
		    foreach ($detaillist as $Kk=>$vva){
		      //  $mapwhere["batchno"]=$vva["norm"];
		      //  $mapwhere["product_code"]=$vva["product_code"];
		      //  $mapwhere["jxs_code"]=$param["jxs_code"];
		      //  $rr=Db::name("product_kucun")->where($mapwhere)->find();
		      //  if($rr){
		      //      $ad=Db::name("product_kucun")->where($mapwhere)->inc("sn_count",1)->update();
		      //  }
		        $finds=Db::name("deliveryorder_fahuo_detail")->where(["wdbh"=>$vva["uid"],"sncode"=>$vva["sncode"]])->order("id desc")->find();
		        Db::name("deliveryorder_fahuo_detail")->where("id",$finds["id"])->update(["is_return"=>1]);
		        Db::name("jxs_kucun")->where(["jxs_code"=>$param["jxs_code"],"sncode"=>$vva["sncode"]])->update(["is_send"=>0]);
		        Db::name("return_apply_detail")->where(["id"=>$vva["id"]])->update(["sh_time"=>time()]);
		        $uuwhere["jxs_code"]=$param["jxs_code"];
		        $uuwhere["product_code"]=$vva["product_code"];
		        $uuwhere["batchno"]=$vva["norm"];
		        Db::name("product_kucun")->where($uuwhere)->inc("sn_count",1)->update();
		        
		    }
		    $ab=Db::name("return_apply")->where("id",$newid)->update(["status"=>1,'update_time'=>date("Y-m-d H:i:s")]);
		    if($ab){
		        Db::commit();
		        return json(['code' => 200,"data"=>"success"]);
		    }else{
		        $result=0;
		        Db::rollback();
		    }
            return json(['code' => $ab,"data"=>"success"]);
        }else if($param["action"] == "no"){
            Db::startTrans();
            $newid=$param["log_id"];
            $detaillist=Db::name("return_apply_detail")->where("return_id",$newid)->select();
		    foreach ($detaillist as $Kk=>$vva){
		        
		        Db::name("jxs_kucun")->where(["jxs_code"=>$vva["uid"],"sncode"=>$vva["sncode"]])->update(["is_send"=>0]);
		        Db::name("return_apply_detail")->where(["id"=>$vva["id"]])->update(["sh_time"=>time()]);
		    }
            $where["id"]=$param["log_id"];
            $update["status"]=2;
            $update["update_time"]=date("Y-m-d H:i:s");
            $rsa=Db::name("return_apply")->where($where)->update($update);
            if($rsa){
		        Db::commit();
		        return json(['code' => 200,"data"=>"success"]);
		    }else{
		        $result=0;
		        Db::rollback();
		    }
            return json(['code' => $rsa,"data"=>"success"]);
        }
        return json(['code' => 1,"data"=>"success"]);
    }
    
    //获取我的审批
    public function get_jxs_shenpi_log(){
        $param = $this->request->param();
        $validate = new Validate([
            'jxs_code' => 'require',
        ]);
        $check_res = $validate->check($param);
        if (!$check_res) {
            return json(['code' => 0, 'message' => $validate->getError()]);
        }
        $jxsinfo=Db::name($this->wx_bos)->where("user_code",$param["jxs_code"])->find();
       
        if($jxsinfo["role"]){
            $usercodes=Db::name($this->wx_bos)->where("parent_id",$jxsinfo["id"])->column("user_code");   
            $datalist=Db::name("return_apply")->where("uid","in",$usercodes)->order("id desc")->select();
        }else{
            $usercodes=Db::name($this->wx_bos)->where("parent_id",24)->column("user_code");   
            $datalist=Db::name("return_apply")->where("uid","in",$usercodes)->order("id desc")->select();
        }
        foreach ($datalist as $kk=>$vv){
            $h["return_id"]=$vv["id"];
            $boxs=Db::name("return_apply_detail")->where($h)->group("boxcode")->count();
            $xn=Db::name("return_apply_detail")->where($h)->group("sncode")->count();
            $vv["boxcode"]=($boxs)?$boxs:0;
            $vv["xn"]=($xn)?$xn:0;
            $datalist[$kk]=$vv;
        }
        return json(['code' => 200,"data"=>$datalist]);
    }
    //获取单个申请单的明细
    public function getbyapply_log(){
        $param = $this->request->param();
        $validate = new Validate([
            'order_no' => 'require',
        ]);
        $check_res = $validate->check($param);
        if (!$check_res) {
            return json(['code' => 0, 'message' => $validate->getError()]);
        }
        $where["id"]=$param["order_no"];
        $datalist=Db::name("return_apply")->where($where)->find();
        $datadetail=[];
        if($datalist){
            $where2["return_id"]=$datalist["id"];
            $datadetail=Db::name("return_apply_detail")->where($where2)->select();
        }
        return json(['code' => 200,"data"=>["order"=>$datalist,"datadetail"=>$datadetail]]);
    }
}
